//
//  UITextView-Extension.swift
//  表情键盘
//
//  Created by 付建国 on 2016/10/20.
//  Copyright © 2016年 sher. All rights reserved.
//

import UIKit

extension UITextView{
    ///获取textview的属性字符串
    func getEmoticonString() -> String{
        //获取属性字符串
        let attrMStr = NSMutableAttributedString.init(attributedString: attributedText)
        //遍历属性字符串
        let range = NSRange.init(location: 0, length: attrMStr.length)
        attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                attrMStr.replaceCharacters(in: range, with: attachment.chs!)
            }
        }
        return attrMStr.string
    }
    
    
    ///给textview插入表情
    func insertEmoticon(emoticon : Emoticon){
        //空白表情
        if emoticon.isEmpty{
            return
        }
        //删除
        if emoticon.isRemove{
            
            deleteBackward()
            return
        }
        //emoji
        if emoticon.emojiCode != nil{
            //获取光标位置
            let textRange = selectedTextRange!
            //替换emoji表情
            replace(textRange, withText: emoticon.emojiCode!)
            
            return
        }
        //普通表情
        //根据图片路径创建属性字符串
        let attachment = EmoticonAttachment()
        attachment.chs = emoticon.chs
        attachment.image = UIImage.init(contentsOfFile: emoticon.pngPath!)
        let font = self.font!
        attachment.bounds = CGRect.init(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
        let attrImageStr = NSAttributedString.init(attachment: attachment)
        
        //创建可变属性字符串
        let attrMStr = NSMutableAttributedString.init(attributedString: attributedText)
        
        //将图片属性字符串，替换到可变属性字符串
        //获取光标位置
        let range = selectedRange
        attrMStr.replaceCharacters(in: range, with: attrImageStr)
        //显示属性字符串
        attributedText = attrMStr
        //将文字大小重置
        self.font = font
        //光标设置到原来位置+1
        selectedRange = NSRange.init(location: range.location + 1, length: 0)
    }
}
